import java.awt.event.*;
import java.awt.*;
import java.io.IOException;
import javax.swing.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.WinDef.UINT_PTR;
import com.sun.jna.win32.*;

public class MyWallpaper {

    static String currentWallpaperPath;

    public static class mButton extends JButton{
        public int index;
        mButton(int num){
            index = num;
        }
    }

    public static void main(String[] argc) throws ParserConfigurationException, SAXException, IOException {
        ///////////////////////////////////////////////////////////
        JFrame jf = new JFrame("Wallpaper");

        JLabel jl = new JLabel("Wallpaper",SwingConstants.LEFT);
        jl.setFont(new Font("Black",Font.BOLD,32));

        JScrollPane jsp = new JScrollPane();

        Box midBox = new Box(BoxLayout.PAGE_AXIS);

        
        JPanel wallPaperType = new JPanel();
        JComboBox jcb = new JComboBox();
        jcb.addItem("Bing");
        jcb.addItem("Image");
        wallPaperType.add(new JLabel("Background: "));
        wallPaperType.add(jcb);


        
        JPanel wallPaperMode = new JPanel();
        JComboBox jcb1 = new JComboBox();
        jcb1.addItem("Tile");
        jcb1.addItem("Zoom");
        jcb1.addItem("Repeat");
        wallPaperMode.add(new JLabel("Position       : "));
        wallPaperMode.add(jcb1);

        JPanel wallpapers=new JPanel(new FlowLayout(FlowLayout.LEFT));
        wallpapers.setPreferredSize(new Dimension(850,850));

        String[] defaultWalls = {
                "C:\\Windows\\Web\\Wallpaper\\Windows\\img0.jpg",
                "C:\\Windows\\Web\\Wallpaper\\Theme1\\img1.jpg",
                "C:\\Windows\\Web\\Wallpaper\\Theme1\\img2.jpg",
                "C:\\Windows\\Web\\Wallpaper\\Theme1\\img3.jpg",
                "C:\\Windows\\Web\\Wallpaper\\Theme1\\img4.jpg",
        };


        mButton[] dButtons = {
                new mButton(0),
                new mButton(1),
                new mButton(2),
                new mButton(3),
                new mButton(4)
        };
        for (int i=0;i<5;++i){
            mButton jlb = dButtons[i];
            Image image=new ImageIcon(defaultWalls[i]).getImage();
            Image smallImage=image.getScaledInstance(100,100,Image.SCALE_FAST);
            jlb.setIcon(new ImageIcon(smallImage));
            jlb.addActionListener(new ActionListener() {
                                       @Override
                                       public void actionPerformed(ActionEvent e) {
                                           currentWallpaperPath = defaultWalls[jlb.index];
                                       }
                                   });
            wallpapers.add(jlb);
        }

        midBox.add(jl);
        midBox.add(wallPaperType);
        midBox.add(wallPaperMode);
        midBox.add(wallpapers);

        midBox.setFont(new Font("Black",Font.PLAIN,16));

        jf.add(midBox); 

        JLabel jb1 = new JLabel("");
        jb1.setPreferredSize(new Dimension(30,30));
        jf.add(jb1,BorderLayout.EAST); 

        JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton apply = new JButton("Apply");
        buttons.add(apply);
        JButton help = new JButton("Help");
        buttons.add(help);
        jf.add(buttons,BorderLayout.SOUTH);

        JLabel jb3 = new JLabel("");
        jb3.setPreferredSize(new Dimension(30,30));
        jf.add(jb3,BorderLayout.WEST);


        jf.setSize(900, 750);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setVisible(true);

        //////////////////////////////////////////////////////////
        apply.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(jcb.getSelectedIndex() ==0){
                    System.out.println("Chosen Bing");
                    bing();
                }else if(jcb.getSelectedIndex() == 1){
                    System.out.println("Chosen manually");
                    setWallpaper();
                }

            }
        });


    }

    public static void customerWallpaper(String currentPath){
        currentWallpaperPath = currentPath;
    }

    public static void setWallpaper(){
        MyWallpaper myWallpaper = new MyWallpaper();
        myWallpaper.settingWallpaper(currentWallpaperPath);
    }

    public static void bing(){
        MyWallpaper myWallpaper = new MyWallpaper();
            try {
                String localPath = new String("C:\\TEMP\\wallpaper.jpg");
                myWallpaper.getThePath();
                String path = myWallpaper.getThePath();
                myWallpaper.downLoadWallpaper(path, localPath);
                myWallpaper.settingWallpaper(localPath);
            }
            catch (Exception e){
                System.out.println(e.toString());
            }

    }

    public interface SPI extends StdCallLibrary {

        long SPI_SETDESKWALLPAPER = 20;
        long SPIF_UPDATEINIFILE = 0x01;
        long SPIF_SENDWININICHANGE = 0x02;

        SPI INSTANCE = (SPI) Native.loadLibrary("user32", SPI.class, new HashMap<Object, Object>() {
            {
                put(OPTION_TYPE_MAPPER, W32APITypeMapper.UNICODE);
                put(OPTION_FUNCTION_MAPPER, W32APIFunctionMapper.UNICODE);
            }
        });

        boolean SystemParametersInfo(UINT_PTR uiAction, UINT_PTR uiParam, String pvParam, UINT_PTR fWinIni);
    }

    public boolean isConnect() throws IOException {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec("ping www.baidu.com");
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        if (br.readLine() == null) {
            // System.out.println("The network is wrong!");
            return false;
        } else {
            // System.out.println("The network is well");
            return true;
        }
    }

    public String getThePath() throws ParserConfigurationException, SAXException, IOException {
        // getting the path of the bing jpg picture via analysis xml
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse("http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=8");
        document.normalize();
        String relativePath = document.getElementsByTagName("url").item(0).getTextContent();
        String path = "http://www.bing.com/" + relativePath;
        return path;
    }

    public void downLoadWallpaper(String path, String localPath) throws IOException {
        // download the jpg file
        path = path.replace("1366x768", "1920x1080");
        URL url = new URL(path);
        DataInputStream dis = new DataInputStream(url.openStream());
        FileOutputStream fos = new FileOutputStream(new File(localPath));
        byte[] buffer = new byte[1024];
        int length;
        while ((length = dis.read(buffer)) > 0) {
            fos.write(buffer, 0, length);
        }

        dis.close();
        fos.close();
    }

    public void settingWallpaper(String localPath) {
        String localpath = localPath;

        SPI.INSTANCE.SystemParametersInfo(new UINT_PTR(SPI.SPI_SETDESKWALLPAPER), new UINT_PTR(0), localpath,
                new UINT_PTR(SPI.SPIF_UPDATEINIFILE | SPI.SPIF_SENDWININICHANGE));
    }
}

